package com.example.cyk.config.exception;

import com.example.cyk.config.response.AppReturn;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ControllerAdvice
public class HandlerException {

    /**
     * 捕获自定义异常
     * @param e
     * @return
     */
    @ResponseBody //返回的是 json 数据，而非页面
    @ExceptionHandler(ApplicationException.class)
    public AppReturn handlerException(ApplicationException e) {
        e.printStackTrace();
        log.error(e.getMessage());
        if(e.getErrorReturn() != null) {
            return e.getErrorReturn();
        }
        return AppReturn.fail(e.getMessage());
    }

    /**
     * 捕获其他异常
     * @param e
     * @return
     */
    @ResponseBody //返回的是 json 数据，而非页面
    @ExceptionHandler(Exception.class)
    public AppReturn handlerException(Exception e) {
        e.printStackTrace();
        log.error(e.getMessage());
        return AppReturn.fail(e.getMessage());
    }

}
